from flask import Blueprint, jsonify, request
from ..models.parking_apron import ParkingApron
from .. import db

bp = Blueprint('parking_aprons', __name__, url_prefix='/api/parking-aprons')

@bp.route('', methods=['GET'])
def get_parking_aprons():
    parking_aprons = ParkingApron.query.all()
    return jsonify([apron.to_dict() for apron in parking_aprons])

@bp.route('/<int:id>', methods=['GET'])
def get_parking_apron(id):
    parking_apron = ParkingApron.query.get_or_404(id)
    return jsonify(parking_apron.to_dict())

@bp.route('', methods=['POST'])
def create_parking_apron():
    data = request.get_json()
    parking_apron = ParkingApron(
        airport_id=data['airport_id'],
        type=data['type'],
        name=data['name'],
        net_depth=data['net_depth'],
        width=data['width'],
        parking_method=data['parking_method'],
        quantity=data['quantity']
    )
    db.session.add(parking_apron)
    db.session.commit()
    return jsonify(parking_apron.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_parking_apron(id):
    parking_apron = ParkingApron.query.get_or_404(id)
    data = request.get_json()
    
    parking_apron.airport_id = data.get('airport_id', parking_apron.airport_id)
    parking_apron.type = data.get('type', parking_apron.type)
    parking_apron.name = data.get('name', parking_apron.name)
    parking_apron.net_depth = data.get('net_depth', parking_apron.net_depth)
    parking_apron.width = data.get('width', parking_apron.width)
    parking_apron.parking_method = data.get('parking_method', parking_apron.parking_method)
    parking_apron.quantity = data.get('quantity', parking_apron.quantity)
    
    db.session.commit()
    return jsonify(parking_apron.to_dict())

@bp.route('/<int:id>', methods=['DELETE'])
def delete_parking_apron(id):
    parking_apron = ParkingApron.query.get_or_404(id)
    db.session.delete(parking_apron)
    db.session.commit()
    return '', 204 